
"use strict";

angular.module('app.project').controller('ProjectDetailCtrl', function ($scope, personalCenterHttp, projectHttpS, jurisHttpS, $http, $rootScope, $stateParams, $cookieStore) {
    
    var pid = $cookieStore.get("view_pid");
    var pcode = $cookieStore.get("view_pcode");
    $rootScope.pname = $cookieStore.get("view_pname");
    var c = false;//温度曲线标记
    //配置分页基本参数
    $scope.paginationConf = {
        currentPage: 1,
        itemsPerPage: 10,
        pagesLength: 5,
        totalItems: 20,
        perPageOptions: [10, 20, 30, 40, 50],

        onChange: function () {
        }
    };

    $("#myTab li a").click(function(){
        // console.log($(this).attr("href").replace("#",""))
        var tab = $(this).attr("href").replace("#","");
        if(tab == "detail"){//油罐数据
            getdetail();
        }else if(tab == "chart"){//温度曲线
            if(!c){
                getchart();
                c = true;
            }
            
        }else if(tab == "ios"){//项目设备信息
            getios();
        }else if(tab == "store"){//油罐信息
            getstore();
        }
    })
    
    var full_pos = 13;
    
    getdetail();
    /***油罐数据* start***/
    function getdetail(){
        $http.get(baseurls+"/detail/project?id=="+pid).then(function(res){
            if(res.data.ret == 1){
                $scope.tankInfo = res.data.info;
                //项目库存信息
                $http.get(baseurls+"/detail/inventory?code=="+pcode).then(function(detail){
                    // console.log(detail.data.info);
                    if(detail.data.ret == 1){
                        $scope.tankInfo.company_name = detail.data.info.company_name;
                        $scope.tankInfo.company_id = detail.data.info.company_id;
                        $scope.tankInfo.item_code = detail.data.info.item_code;
                        $scope.tankInfo.item_name = detail.data.info.item_name;
                        $scope.tankInfo.qty = detail.data.info.qty;
                        $scope.tankInfo.y_qty = detail.data.info.y_qty;
                        $scope.tankInfo.l_qty = detail.data.info.l_qty;
                        $scope.tankInfo.unit = detail.data.info.unit;
                    }
                })
                //项目实时信息
                $http.get(baseurls+"/list_nopage/device?projectid=="+pid).then(function(real){
                    // console.log(real.data)
                    if(real.data.ret==1){
                        if(real.data.info.length != 0){//有设备
                            $scope.real_device = real.data.info[0].deviceid;
                            //实时数据
                            $http.post(baseurls+"/list/select/yk_datasub?deviceid=="+$scope.real_device).then(function(realdata){
                                // console.log(realdata.data)
                                if(realdata.data.ret == 1){
                                    var len = realdata.data.rows.length;
                                    
                                    for(var k=0; k<len; k++){
                                        if($scope.tankInfo.avg_temp == undefined || $scope.tankInfo.real_pos == undefined || $scope.tankInfo.pos_present == undefined){
                                            var con = realdata.data.rows[k].sensor_num == 12;//温度数据
                                            // console.log(con);
                                            switch (con) {
                                                case true:
                                                    var thermometer = realdata.data.rows[k].value.replace("[","").replace("]","").split(",");
                                                    var temp = 0;
                                                    $scope.thermometers = [];
                                                    for(var q=0;q<thermometer.length;q++){
                                                        // console.log(q)
                                                        var value = parseFloat(thermometer[q])/Math.pow(10,realdata.data.rows[k].point_num);
                                                        if(value!=0){
                                                            if(realdata.data.rows[k].dm == 1) value = -value;
                                                        }
                                                        temp += value;
                                                        $scope.thermometers[q] = {"value":value};
                                                        // console.log($scope.thermometers[q]+" : "+thermometer[q])
                                                    }
                                                    // console.log($scope.thermometers);
                                                    $scope.tankInfo.avg_temp = temp/12;
                                                    break;
                                                case false:
                                                    
                                                    var value = realdata.data.rows[k].value.replace("[","").replace("]","");
                                                    value = parseFloat(value)/Math.pow(10,realdata.data.rows[k].point_num);
                                                    if(value!=0){
                                                        if(realdata.data.rows[k].dm == 1) value = -value;
                                                    }
                                                    $scope.tankInfo.real_pos = value;
                                                    $scope.tankInfo.pos_present = (parseFloat(value)/full_pos)*100+"%";
                                                    break;
                                                // default:
                                                    // ...
                                            }
                                        }else{

                                        }
                                    }
                                    

                                }
                            })
                        }else{//项目没有绑定数据
                            $scope.tankInfo.avg_temp = 0;
                            $scope.tankInfo.real_pos = 0;
                            $scope.tankInfo.pos_present = 0;
                            $scope.thermometers = [];
                        }
                    }else{//项目没有绑定数据
                        $scope.tankInfo.avg_temp = 0;
                        $scope.tankInfo.real_pos = 0;
                        $scope.tankInfo.pos_present = 0;
                        $scope.thermometers = [];
                    }
                })
                
            }
            // console.log($scope.tankInfo)
        })
    
        //编辑温度计高度 和报警温度
        /*
        $scope.edit = function(tid){
            console.log(tid)
            var high = $('.detail-right-table tr:eq('+(tid+1)+')').children('td:eq(1)').html();
            var alert = $('.detail-right-table tr:eq('+(tid+1)+')').children('td:eq(2)').html();
            console.log(high,alert)
            $('.detail-right-table tr:eq('+(tid+1)+')').children('td:eq(1)').html('<input type="text" class="input-xs high-input" style="width:58px" value="'+high+'" />')
                                .next().html('<input type="text" class="input-xs alert-input" style="width:58px" value="'+alert+'" />')
                                .next().children('.btn-edit').hide().parent().append('<button class="btn btn-success btn-ok" style="padding:1px 5px;"><i class="fa fa-check"></i></button>')
                                
    
            $('.btn-ok').click(function(){
                var new_high = parseFloat($('.high-input').val());
                var new_alert = parseFloat($('.alert-input').val());
                $scope.new_therm = $scope.thermometer;
                $scope.new_therm_arr = $scope.tankInfo.detail.thermometer;
                for(var i=0;i<$scope.new_therm.length;i++){
                    if($scope.new_therm[i].tid == tid){
                        $scope.new_therm[i].high = new_high;
                        $scope.new_therm[i].alert = new_alert;
                        $scope.new_therm_arr[i] = 'h'+new_high+'a'+new_alert;
                    }
                }
                $scope.new_therm = JSON.stringify($scope.new_therm)
                console.log($scope.new_therm)
                $scope.new_therm_arr = JSON.stringify($scope.new_therm_arr)
                console.log($scope.new_therm_arr)
                // $http.put(baseurls+"/data/project_detail?id=="+pid,{thermometer:$scope.new_therm}).then(function(res){
                //     // console.log(res.data)
                //     if(res.data.ret == 1 ) console.log('ok')
                // })
                $http.put(baseurls+"/data/project?id=="+pid,{detail:JSON.stringify({thermometer:$scope.new_therm_arr})}).then(function(res){
                    console.log(res.data) //？？？
                    if(res.data.ret == 1 ) console.log('ok')
                })
                $(this).parents('tr').children('td:eq(1)').html($('.high-input').val())
                                    .next().html($('.alert-input').val())
                                    .next().children('.btn-edit').show().parent().children('.btn-ok').remove();
            })
        }*/
    }
    /***油罐数据* end***/
    
    /***温度曲线 start***/
    function getchart(){
        var datasets = [
            {
                label: "温度计1",
                data: [[1988, 48], [1989, 47], [1990, 45], [1991, 40], [1992, 42], [1993, 40], [1994, 37], [1995, 35], [1996, 33], [1997, 33], [1998, 32], [1999, 32], [2000, 34.2], [2001, 34.4], [2002, 38.7], [2003, 44], [2004, 48], [2005, 38], [2006, 52]]
            },        
            {
                label: "温度计2",
                data: [[1988, 21.8], [1989, 20.3], [1990, 17.1], [1992, 42.5], [1993, 37.6], [1994, 36.6], [1995, 21.7], [1996, 19.2], [1997, 21.3], [1998, 13.6], [1999, 14.0], [2000, 19.1], [2001, 21.3], [2002, 23.6], [2003, 25.1], [2004, 26.1], [2005, 31.1], [2006, 34.7]]
            },
            {
                label: "温度计3",
                data: [[1988, 29], [1989, 27], [1990, 26], [1991, 23], [1992, 26], [1993, 23], [1994, 29], [1995, 25], [1996, 24], [1997, 26], [1998, 21], [1999, 24], [2000, 28], [2001, 26], [2002, 25], [2003, 22], [2004, 26], [2005, 26], [2006, 23]]
            },
            {
                label: "温度计5",
                data: [[1988, 37], [1989, 35], [1990, 34], [1991, 34], [1992, 36], [1993, 39], [1994, 32], [1995, 38], [1996, 35], [1997, 34], [1998, 33], [1999, 32], [2000, 37], [2001, 34], [2002, 34], [2003, 34], [2004, 36], [2005, 30], [2006, 34]]
            },
            {
                label: "温度计6",
                data: [[1988, 11.3], [1989, 11.9], [1990, 12.2], [1991, 18.9], [1992, 12.0], [1993, 13.0], [1994, 13.6], [1995, 19.8], [1996, 10.6], [1997, 15.5], [1998, 19.5], [1999, 17.3], [2000, 15.3], [2001, 17.4], [2002, 12.8], [2003, 11.8], [2004, 13.8], [2005, 16.7], [2006, 17.0]]
            },
            {
                label: "温度计7",
                data: [[1988, 10.2], [1989, 17.4], [1990, 10.5], [1991, 10.9], [1992, 13.5], [1993, 12.0], [1994, 10.0], [1995, 11.8], [1996, 15.8], [1997, 18.0], [1998, 15.4], [1999, 17.8], [2000, 11.1], [2001, 19.3], [2002, 13.3], [2003, 19.1], [2004, 15.0], [2005, 12.1], [2006, 17.1]]
            },
            {
                label: "温度计8",
                data: [[1988, 28.2], [1989, 29.8], [1990, 23.5], [1991, 29.8], [1992, 26.6], [1993, 24.1], [1994, 27.0], [1995, 21.7], [1996, 27.5], [1997, 20.3], [1998, 28.2], [1999, 20.6], [2000, 25.8], [2001, 28.5], [2002, 26.9], [2003, 26.6], [2004, 29.4], [2005, 28.7], [2006, 29.1]]
            }
        ];
    
        // hard-code color indices to prevent them from shifting as
        // countries are turned on/off
    
        var i = 0;
        $.each(datasets, function(key, val) {
            val.color = i;
            ++i;
        });
    
        // insert checkboxes 
        var choiceContainer = $("#choices");
        $.each(datasets, function(key, val) {
            // console.log(val)
            choiceContainer.append(
                // "<br/><input type='checkbox' name='" + key +
                // "' checked='checked' id='id" + key + "'></input>" +
                // "<label for='id" + key + "'>"
                // + val.label + "</label>"
                '<div class="col-xs-4 col-md-3 col-lg-2">'+
                    '<div class="well text-center connect">'+
                        // '<img src="styles/img/avatars/gril1.png" alt="img" class="margin-bottom-5 margin-top-5">'+
                        '<div class="margin-bottom-5 margin-top-5" style="border-radius:50% 50% 0; background:#2b92ea; width:50px; height:50px; display:inline-block">'+
                            '<strong style="color:#fff; line-height:50px;">'+val.data[val.data.length-1][1].toFixed(1)+'°C</strong>'+
                        '</div>'+
                        '<br>'+
                        '<span class="font-xs"><b>'+val.label+'</b></span>'+
                        '<br>'+
                        '<span class="onoffswitch">'+
                            '<input type="checkbox" name="'+key+'" checked="checked" class="onoffswitch-checkbox ng-untouched ng-valid ng-dirty ng-valid-parse" id="id'+key+'">'+
                            '<label class="onoffswitch-label" for="id'+key+'">'+
                                '<span class="onoffswitch-inner" data-swchon-text="显示" data-swchoff-text="隐藏"></span>'+
                                '<span class="onoffswitch-switch"></span>'+
                            '</label>'+
                        '</span>'+
                    '</div>'+
                '</div>'
            );
        });
    
        choiceContainer.find("input").click(plotAccordingToChoices);
    
        function plotAccordingToChoices() {
    
            var data = [];
    
            choiceContainer.find("input:checked").each(function () {
                var key = $(this).attr("name");
                if (key && datasets[key]) {
                    data.push(datasets[key]);
                }
            });
    
            if (data.length > 0) {
                $.plot("#tempcharts", data, {
                    series: {
                        lines: {
                            show: true,
                            lineWidth: 2
                        },
                        points:{
                            show: true
                        }
                    },
                    grid: { 
                        hoverable: true, 
                        clickable: true, 
                        tickColor: "#dddddd",
                        borderWidth: 2 
                    },
                    yaxis: {
                        min: 0,
                        tickDecimals: 2 //y轴小数点位数
                    },
                    xaxis: {
                        // mode: "time", //x轴显示时间数据格式
                        // tickSize:[1, "day"], //刻度标签会以每1天的间隔显示
                        // timeformat: "%Y/%m/%d", //刻度标签要输出的格式
                        // rotateTicks: 45, //jquery.flot.tickrotor 控制x轴过长时的倾斜
                        // labelWidth: 150,
                        // labelHeight: 150,
                        // reserveSpace: true,
                        tickDecimals: 0 //x轴小数点位数
                    },
                    legend: {//???
                        show: true,
                        noColumns: 0,
                            labelFormatter: function (label, series) {
                                return "<font size=\"2\" color=\"white\">" + label + "</font>";
                        },            
                        backgroundColor: "#000",
                        backgroundOpacity: 0.9,
                        labelBoxBorderColor: "#000000",
                        position: "nw"
                    }
                });
    
                function showTooltip(x, y, contents) {
                    $('<div id="tooltip">' + contents + '</div>').css( {
                        position: 'absolute',
                        display: 'none',
                        top: y + 5,
                        left: x + 5,
                        border: '1px solid #fdd',
                        padding: '2px',
                        'background-color': '#dfeffc',
                        opacity: 1,
                        'z-index': 1000
                    }).appendTo("body").fadeIn(200);
                }
    
                var previousPoint = null;
                $("#tempcharts").bind("plothover", function (event, pos, item) {
                    $("#x").text(pos.x);
                    $("#y").text(pos.y.toFixed(2));
    
                    if (item) {
                        if (previousPoint != item.dataIndex) {
                            previousPoint = item.dataIndex;
    
                            $("#tooltip").remove();
                            var x = new Date(item.datapoint[0]).toLocaleString(),//时间戳毫秒数转换成日期时间
                                y = item.datapoint[1].toFixed(2);
    
                            showTooltip(item.pageX, item.pageY,
                                        item.series.label + " 在 " + x + " 的值是 " + y +"°C");
                        }
                    }
                    else {
                        $("#tooltip").remove();
                            previousPoint = null;
                    }
                }); 
                
            }
        }
        plotAccordingToChoices();
    }
    /***温度曲线 start***/

    /***设备信息* start***/
    function getios(){
        //当前项目的设备信息
        $http.post(baseurls+"/list/select/device?projectid=="+pid, $scope.paginationConf).then(function(res){
            // console.log(res.data)
            if(res.data.ret == 1){
                $scope.devices = res.data.rows;
                $scope.paginationConf.totalItems = res.data.records;
            }
        })
    }
    /***设备信息* end***/

    /***油罐信息* start***/
    $scope.infor = {}; // 油罐基本信息
    function getstore(){
        if(pid){
            //项目基本信息
            $http.get(baseurls+"/detail/project?id=="+pid,{withCredentials:true}).then(function(res){
                console.log(res.data.info);
                if(res.data.ret == 1){
                    $scope.infor = res.data.info;
                }
            })
            //项目库存信息
            $http.get(baseurls+"/detail/inventory?code=="+pcode,{withCredentials:true}).then(function(res){
                console.log(res.data);
                if(res.data.ret == 1){
                    $scope.store = res.data.info;
                }else{
                    //无库存信息
                }
            })
        }
    }
    /***油罐信息* end***/
  
});